package ch9;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XmlReader {

	public static void main(String[] args) {
		SAXReader reader = new SAXReader();
		List<Cloth> l2 = new ArrayList<>();
		try {
			// jar
			// Document doc = reader.read(new File("src/ch9/clothes.xml"));
			Document doc = reader.read(XmlReader.class.getClassLoader().getResourceAsStream("ch9/clothes.xml"));
			Element root = doc.getRootElement();
			System.out.println("根节点的名称是：" + root.getName());
			// doc.selectNodes("/clothes/cloth");
			// root.elements():所有子节点

			List<Element> list = root.selectNodes("cloth");
			for (Element e : list) {
				// 获得属性
				String chandi = e.attributeValue("chandi");
				String yanse = e.attributeValue("color");
				// Element brand = (Element) e.selectNodes("brand").get(0);
				Element brand = (Element) e.selectSingleNode("brand");
				String b = brand.getText();
				String price = e.selectSingleNode("price").getText();
				double jiage = Double.parseDouble(price);
				Element su = (Element) e.selectSingleNode("suit");
				String suit = su == null ? "" : su.getText();

				System.out.println(b + "," + jiage + ",适合" + suit + ",产地：" + chandi + ",颜色：" + yanse);
				System.out.println(">>>>>>>>>>>>>>");

				Cloth c = new Cloth(b, yanse, chandi, suit, jiage);
				l2.add(c);
			}
		} catch (DocumentException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		for (Cloth cc : l2)
			System.out.println(cc);
	}

}
